#include "head.h"

int ser_rmdir(int fd, transport_protocol_t *test){
    int i = 0;
    int flag;
    char str[40] = {0};
    MYSQL_RES *result;
    MYSQL_ROW row;
    while(1){ // 循环判断对方是否跨目录删除目录
        if(test->buf[i] == '\0'){
            break;
        }
        if(test->buf[i] == '/'){
            flag = -1;
            send(fd, &flag, sizeof(int), 0);
            return 0;
        }
        i++;
    }
    if(strcmp(test->curr_path, "/") == 0){
        bzero(test->curr_path, sizeof(test->curr_path));
    }
    char buffer[1024] = {0};
    
    sprintf(buffer, "select file_id from bd_file where user_id = %s"
        " and filename = '%s' and url = '%s/%s' and delete_flag=0",
        test->user_id, test->buf, test->curr_path, test->buf);
    mysql_query(&test->my_sql, buffer);
    if(mysql_error(&test->my_sql) != NULL){
        sprintf(str,"mkdir mysql_error:%s", mysql_error(&test->my_sql));
        LOG_WRITE( 3, str);
    }

    result = mysql_store_result(&test->my_sql);
    // 如果不为0行，说明该目录存在获取file_id
    char buf4[10] = {0};
    if(mysql_num_rows(result) != 0){
        unsigned int files = mysql_num_fields(result);
        while((row = mysql_fetch_row(result)) != NULL){
            for(unsigned int i = 0; i < files; i++){
                sprintf(buf4, "%s",row[i]);
            }
            printf("\n");
        }
        sprintf(str, "buf4:%s",buf4);
        LOG_WRITE(2, str);
        mysql_free_result(result);
    }else{
        // printf("当前路径没有这个目录\n");
        flag = -1;
        send(fd, &flag, sizeof(int), 0);
        return 0;
    }
      
    bzero(buffer, sizeof(buffer));
    sprintf(buffer, "select *from bd_file where user_id = %s"
            " and parent_id = %s and delete_flag=0",
            test->user_id, buf4);
    mysql_query(&test->my_sql, buffer);
    if(mysql_error(&test->my_sql) != NULL){
        sprintf(str,"mkdir mysql_error:%s", mysql_error(&test->my_sql));
        LOG_WRITE( 3, str);
    }
    int ret = sql_watch(&test->my_sql);
    if(ret == 0){ // 目录有文件存在，无法删除
        flag = -1;
        send(fd, &flag, sizeof(int), 0);
        return 0;
    }
    // 运行到此处说明文件目录为空
    bzero(buffer, sizeof(buffer));
    sprintf(buffer,"update bd_file set delete_flag = 1 where "
        "user_id = %s and filename = '%s' and url = '%s/%s'",
        test->user_id, test->buf, test->curr_path,test->buf);
    mysql_query(&test->my_sql, buffer);
    
    bzero(str, sizeof(str));
    if(mysql_error(&test->my_sql) != NULL){
        sprintf(str,"mkdir mysql_error:%s", mysql_error(&test->my_sql));
        LOG_WRITE( 3, str);
    }
    
    flag = 0;
    send(fd, &flag, sizeof(int), 0);

    return 0;
}


